﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Microsoft.BizTalk.Streaming;

namespace Locallab.Ack999Helper.BusinessContextReader
{
    internal class X12837Reader : X12Reader,IX12Reader
    {        
        private BusinessContext bContext = null;

        public void ProcessX12Stream(FileHeaderData delimiter, ReadOnlySeekableStream x12MessageStream,StreamReader x12Reader)
        {
            base.delimiter = delimiter;
            base.ProcessX12Stream(x12MessageStream,x12Reader);
        }

        public override void ProcessEdiSegment(EdiSegment segment)
        {
            switch (segment.Name)
            {
                case "HL":
                    ProcessHL(segment);
                    break;

                case "CLM":
                    ProcessCLM(segment);
                    break;

                case "ST":
                    {                        
                        bContext = null;
                    }
                    break;

                case "SE":
                    {
                        if (bContext != null)
                        {
                            bContext.EndIndex = segment.LineNumber - 1;
                            SaveBusinessIdentifier(bContext);
                        }
                    }
                    break;

                default:
                    break;
            }
        }

        private void ProcessHL(EdiSegment segment)
        {
            var strArrayElements = Utility.SplitSegment(segment.Data, this.delimiter.ElementDelimiter);

            if (strArrayElements.Length < 4)
                return;

            if ((strArrayElements[3] == "22") || (strArrayElements[3] == "23"))
            {
                if (bContext == null)
                {
                    bContext = new BusinessContext();
                }

                if (bContext.IsProcessed)
                {
                    bContext.EndIndex = segment.LineNumber - 1;
                    SaveBusinessIdentifier(bContext);
                    bContext.StartIndex = segment.LineNumber;
                    bContext.IsProcessed = false;
                }
                else
                {
                    bContext.StartIndex = segment.LineNumber;
                }
            }            
        }        

        private void ProcessCLM(EdiSegment segment)
        {
            var strArrayElements = Utility.SplitSegment(segment.Data, this.delimiter.ElementDelimiter);
            bContext.BusinessIDQualifier = "CLM01";
            bContext.BusinessID = strArrayElements[1].Trim();
            bContext.FileLineNumber = segment.FileLineNumber;
            bContext.IsProcessed = true;
        }        
    }
}
